﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GestorSQL.BLL;
using GestorSQL.BLL.ImplementationsBridge;
using GestorSQL.Security.Interface;
using GestorSQL.BusinessEntities;

namespace GestorSQL.GUI.UsersInRoles
{
    public partial class RolesManagement : Form
    {
        private SecurityManager _securityManager = new SecurityManager();
        private AssignmentsManager _assigmentsManager = new AssignmentsManager();
        private IUserManager userManager = null;
        private bool isValidUser = false;
        private string userName;

        #region Constructores
        public RolesManagement()
        {
            InitializeComponent();
            dGridRoles.DataSource = _securityManager.GetRoleList();
            userManager = ImplementationBridge.GetUserManagerImplementation();
        }

        public RolesManagement(string userName)
        {
            InitializeComponent();

            dGridRoles.DataSource = _securityManager.GetRoleList();
            userManager = ImplementationBridge.GetUserManagerImplementation();

            this.userName = userName;
            tbUsuario.Text = userName;
            tbUsuario.Font = new Font(this.Font, FontStyle.Regular);
            tbUsuario.ReadOnly = true;

            btnBuscar.Enabled = false;

            fillRolesGrid(_securityManager.GetRolesByUserName(userName));
        }
        #endregion

        #region Eventos

        private void btnBuscar_Click(object sender, EventArgs e)
        {
            string fullName = string.Empty;
            isValidUser = false;

            tbUsuario.Font = new Font(this.Font, FontStyle.Regular);

            userName = tbUsuario.Text.Trim();

            if (string.IsNullOrEmpty(userName))
            {



                MessageBox.Show(Properties.Resources.Roles_UserNameEmptyText, Properties.Resources.ErrorText, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (isValidUser = userManager.ExistUser(userName, ref fullName))
            {
                tbUsuario.Font = new Font(this.Font, FontStyle.Underline);
                tbUsuario.Text = fullName;
            }
            else
                MessageBox.Show(string.Format(Properties.Resources.Roles_UserNotExistText, userName));
        }

        private void tbUsuario_TextChanged(object sender, EventArgs e)
        {

            tbUsuario.Font = new Font(this.Font, FontStyle.Regular);
        }

        public void fillRolesGrid(List<Role> roleList)
        {

            List<int> selecccionados = new List<int>();

            foreach (DataGridViewRow dgRow in dGridRoles.Rows)
            {
                if (roleList.Where(x => x.IdRole == (dgRow.DataBoundItem as Role).IdRole).Count() > 0)
                {
                    DataGridViewCheckBoxCell dgCb = dgRow.Cells["Seleccionado"] as DataGridViewCheckBoxCell;
                    dgCb.Value = true;
                }
            }
            dGridRoles.CommitEdit(DataGridViewDataErrorContexts.Commit);

            dGridRoles.Refresh();

        }

        /// <summary>
        /// Evento Guardar Asignación de los roles al usuario
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGuardar_Click(object sender, EventArgs e)
        {
            Role roleSelected = null;
            List<Role> rolesList = new List<Role>();
            string fullName = string.Empty;

            if (string.IsNullOrEmpty(userName))
            {
                MessageBox.Show(Properties.Resources.Roles_UserNameEmptyText, Properties.Resources.ErrorText, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            dGridRoles.CommitEdit(DataGridViewDataErrorContexts.Commit);

            if (userManager.ExistUser(userName, ref fullName))
            {
                foreach (DataGridViewRow dgRow in dGridRoles.Rows)
                {
                    DataGridViewCheckBoxCell dgCb = (dgRow.Cells["Seleccionado"] as DataGridViewCheckBoxCell);
                    if (((bool)dgCb.FormattedValue))
                    {
                        roleSelected = (dgRow.DataBoundItem as Role);
                        rolesList.Add(roleSelected);
                    }
                }

                if (!_securityManager.ExistUserOnGestorSQL(userName) && rolesList.Count() > 0)
                {
                    if (_securityManager.SaveUserInRole(userName, rolesList).Equals(Resultado.Exitoso))
                    {
                        if (rolesList.Select(x => x.Nombre.Equals(Role.AUTORIZADOR.ToString())).Count() > 0)
                            _assigmentsManager.CrearAsignacion(userName);


                        this.Close();
                        this.DialogResult = DialogResult.OK;
                    }
                    else
                        MessageBox.Show(Properties.Resources.Roles_ErrorSaveUserRoles);

                }
                else if (_securityManager.UpdateUserInRoles(tbUsuario.Text.Trim(), rolesList).Equals(Resultado.Exitoso))
                {
                    if (rolesList.Select(x => x.Nombre.Equals(Role.AUTORIZADOR.ToString())).Count() == 0)
                        _assigmentsManager.EliminarAsignacion(userName);

                    this.Close();
                    this.DialogResult = DialogResult.OK;
                }
            }
            else
                MessageBox.Show(string.Format(Properties.Resources.Roles_UserNotExistText, userName));
        }

        #endregion


    }
}
